//
//  AMTMP3Process.m
//  LameSample
//
//  Created by yao on 3/19/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AMTMP3Process.h"


@implementation AMTMP3Process

-(id) initWithParam:(NSString*)bit withFrequency:(NSString*)f {
	bitrate = bit == nil ? @"-b 128" : [NSString stringWithFormat:@"-b %@", bit];
	[bitrate retain];
	frequency = f == nil ? @"-s 44.1" : [NSString stringWithFormat:@"-s %@", f];
	[frequency retain];
	return self;
}

-(void) setParam:(NSString*)bit withFrequency:(NSString*)f {
	bitrate = bit;
	frequency = f;
}

-(BOOL) convertOneToMP3:(NSString*)inPath to:(NSString*)outPath {
	NSTask *task;
	task = [[NSTask alloc] init];
	NSString* lamePath = [[NSBundle mainBundle] pathForResource:@"lame" ofType:nil];
	
	[task setLaunchPath: lamePath];
	
	NSArray* arguments = [NSArray arrayWithObjects:@"-h", bitrate, frequency, inPath, outPath, nil];
	[task setArguments:arguments];
	
	NSPipe *pipe;
	pipe = [NSPipe pipe];
	[task setStandardOutput: pipe];
	
	[task waitUntilExit];
	
	NSFileHandle *file;
	file = [pipe fileHandleForReading];
	
	[task launch];
	
	NSData *data;
	data = [file readDataToEndOfFile];
	
	NSString *string;
	string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
	NSLog(string);
	
	if([string rangeOfString:@"Warning: unsupported audio format"].length > 0)
	{
		[string release];
		return NO;
	}
	[string release];
	[task release];
	return YES;
}

/*
 *	xld [-c cuesheet] [-e] [-f format] [-o outpath] [-t track] file
 *
 */
-(BOOL) convertOtherToMP3:(NSString*)inPath to:(NSString*)outPath {
	NSRange fnBegin = [inPath rangeOfString:@"/" options:NSBackwardsSearch];
	NSString* wavOutFolder = [inPath substringToIndex:fnBegin.location];
	NSString* inFilename = [inPath substringFromIndex:fnBegin.location];
	NSRange fnEnd = [inFilename rangeOfString:@"."];
	NSString* filename = [inFilename substringToIndex:fnEnd.location];
	
	NSTask *task;
	task = [[NSTask alloc] init];
	NSString* xldPath = [[NSBundle mainBundle] pathForResource:@"xld" ofType:nil];
	
	[task setLaunchPath: xldPath];
	
	NSArray* arguments = [NSArray arrayWithObjects:@"-f", @"wav", inPath, nil];
	[task setArguments:arguments];
	
	NSPipe *pipe;
	pipe = [NSPipe pipe];
	[task setStandardOutput: pipe];
	
	[task waitUntilExit];
	
	NSFileHandle *file;
	file = [pipe fileHandleForReading];
	
	[task launch];
	
	NSData *data;
	data = [file readDataToEndOfFile];
	
	NSString *string;
	string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
	NSLog(string);
	/*
	if([string rangeOfString:@"Warning: unsupported audio format"].length > 0)
	{
		[string release];
		return NO;
	}
	*/
	
	NSString* wavFilepath = [NSString stringWithFormat:@"%@.wav", [wavOutFolder stringByAppendingPathComponent:filename]];
	NSFileManager* fileManager = [NSFileManager defaultManager];
	BOOL success = NO;
	if([fileManager fileExistsAtPath:wavFilepath])
	{
		if([self convertOneToMP3:wavFilepath to:outPath])
			success = YES;
		[fileManager removeItemAtPath:wavFilepath error:nil];
	}
	
	[string release];
	[task release];
	
	return success;
}

-(NSArray*) convertSomeToMP3:(NSArray*)inPaths to:(NSString*)outDirectory {
	NSMutableArray* failedFiles = [NSMutableArray array];
	NSFileManager* fileManager = [NSFileManager defaultManager];
	if(![fileManager fileExistsAtPath:outDirectory])
		[fileManager createDirectoryAtPath:outDirectory attributes:nil];
	for(NSString* inPath in inPaths)
	{
		if(![fileManager fileExistsAtPath:inPath])
			continue;
		NSRange fnBegin = [inPath rangeOfString:@"/" options:NSBackwardsSearch];		
		NSString* inFilename = [inPath substringFromIndex:fnBegin.location];
		NSRange fnEnd = [inFilename rangeOfString:@"."];
		NSString* filename = [inFilename substringToIndex:fnEnd.location];
		NSString* ext = [inFilename substringFromIndex:fnEnd.location];
		NSString* outFilename = [NSString stringWithFormat:@"%@.mp3", filename];
		
		int i = 1;
		NSString* outPath;
		while (TRUE)
		{
			outPath = [outDirectory stringByAppendingPathComponent:outFilename];
			if(![fileManager fileExistsAtPath:outPath])
			{
				NSRange extRange = [ONE_TYPE rangeOfString:ext];
				if(extRange.length > 0)
				{
					if(![self convertOneToMP3:inPath to:outPath])
						[failedFiles addObject:inFilename];
				}
				extRange = [OTHER_TYPE rangeOfString:ext];
				if(extRange.length > 0)
				{
					if(![self convertOtherToMP3:inPath to:outPath])
						[failedFiles addObject:inFilename];
				}
				break;
			}
			else
			{
				outFilename = [NSString stringWithFormat:@"%@(%d).mp3", filename, i];
				i++;
			}
		}
	}
	return failedFiles;
}

- (void)dealloc {
	[frequency release];
	[bitrate release];
	[super dealloc];
}

@end
